placebo_analysis <- function(
  data, min_day = -30, max_day = 30, verbose = TRUE
) {

  # initial binding of globals
  `%>%` <- magrittr::`%>%`
  unit <- grid::unit
  element_rect <- ggplot2::element_rect
  aes <- ggplot2::aes
  relative_date <- win_cabinet <- winners_beta <- NULL
  losers_beta <- NULL

  # binary variable which captures whether the government was formed or not
  data <- dplyr::mutate(.data = data, gov_formed = ifelse(
    test = relative_date > 0, yes = 1, no = 0
  ))

  # drop observations at government formation day because it is not clear
  # whether they could know about the government formation or not at the time
  # they were interviewed
  data <- dplyr::filter(.data = data, relative_date != 0)

  # split sample into winners and losers
  df_winners <- dplyr::filter(.data = data, win_cabinet == 1)
  df_losers <- dplyr::filter(.data = data, win_cabinet == 0)

  # Average difference in swd before and after gov formation
  pre_post_winners <- lm(
    formula = swd ~ gov_formed + election,
    data = df_winners,
    subset = relative_date >= min_day & relative_date <= max_day
  )
  pre_post_losers <- lm(
    formula = swd ~ gov_formed + election,
    data = df_losers,
    subset = relative_date >= min_day & relative_date <= max_day
  )

  summary(pre_post_winners)
  summary(pre_post_losers)

  # Instead of post-government formation date use a randomly-chosen time, then
  # estimate pre v post and compare difference to the placebo distribution


  # simulation --------------------------------------------------------------
  set.seed(123)
  nsims <- 10000

  # create progress bar
  if (verbose) {
    pb <- utils::txtProgressBar(min = 1, max = nsims, style = 3)
  }


  # loop over simulation iterations
  df_betas <- lapply(X = seq(1:nsims), FUN = function(x) {

    # draw a random cutoff date
    cutoff <- as.integer(runif(n = 1, min = min_day, max = max_day + 1))

    # generate placebo government formation date
    df_winners <- dplyr::mutate(.data = df_winners, placebo_gov_formed = ifelse(
      test = relative_date > cutoff, yes = 1, no = 0
    ))
    df_losers <- dplyr::mutate(.data = df_losers, placebo_gov_formed = ifelse(
      test = relative_date > cutoff, yes = 1, no = 0
    ))

    # mean difference in swd
    m_winners <- lm(
      formula = swd ~ placebo_gov_formed + election,
      data = df_winners,
      subset = relative_date >= (cutoff + min_day) &
        relative_date <= (cutoff + max_day)
    )
    m_losers <- lm(
      formula = swd ~ placebo_gov_formed + election,
      data = df_losers,
      subset = relative_date >= (cutoff + min_day) &
        relative_date <= (cutoff + max_day)
    )

    # update progress bar
    if (verbose) {
      utils::setTxtProgressBar(pb = pb, value = x)
    }

    # store results
    results <- tibble::tibble(
      placebo_cutoff = cutoff,
      winners_beta = coefficients(m_winners)["placebo_gov_formed"],
      losers_beta = coefficients(m_losers)["placebo_gov_formed"]
    )

    return(results)
  })

  # close progress bar
  if (verbose) {
    close(pb)
  }

  # observed difference
  actual_est_winners <- coefficients(pre_post_winners)["gov_formed"]
  actual_est_losers <- coefficients(pre_post_losers)["gov_formed"]

  # one-sided p-value
  df_betas <- df_betas %>%
    dplyr::bind_rows(df_betas)
  pv_winners <- mean(
    dplyr::pull(.data = df_betas, var = winners_beta) >= actual_est_winners
  )
  pv_losers <- mean(
    dplyr::pull(.data = df_betas, var = losers_beta) <= actual_est_losers
  )

  # plot results ------------------------------------------------------------

  # x-axis limits
  x_lower_winners <- plyr::round_any( # nolint
    x = min(df_betas$winners_beta),
    accuracy = 1e-1, f = floor
  )
  x_lower_losers <- plyr::round_any( # nolint
    x = min(df_betas$losers_beta),
    accuracy = 1e-1, f = floor
  )
  x_upper_winners <- plyr::round_any( # nolint
    x = max(df_betas$winners_beta),
    accuracy = 1e-1, f = ceiling
  )
  x_upper_losers <- plyr::round_any( # nolint
    x = max(df_betas$winners_beta),
    accuracy = 1e-1, f = ceiling
  )

  # plot theme
  ggplot2::theme_set(new = ggthemes::theme_wsj(base_size = 9))
  ggthemes::theme_wsj

  #### winners plot
  winners_plot <- ggplot2::ggplot(
    data = df_betas, mapping = ggplot2::aes(x = winners_beta)
  ) +
    ggplot2::geom_density(color = "black", fill = "gray") +
    ggplot2::geom_vline(
      xintercept = actual_est_winners, linetype = "dashed", size = 1
    ) +
    ggplot2::geom_segment(aes(
      x = actual_est_winners + 0.1,
      xend = actual_est_winners + 0,
      y = 4.6,
      yend = 4.6
    ),
    arrow = ggplot2::arrow(length = unit(2, "mm"))
    ) +
    ggplot2::annotate(
      geom = "text", x = actual_est_winners + 0.12, y = 4.6,
      label = "Observed difference", hjust = "left"
    ) +
    ggplot2::annotate(
      geom = "text", x = actual_est_winners + .12, y = 4.3,
      label = paste0("(p-value=", round(pv_winners, 2), ")"),
      hjust = "left"
    ) +
    ggplot2::labs(
      title = "Electoral Winners",
      x = "Difference in Satisfaction with Democracy",
      y = "Density"
    ) +
    ggplot2::scale_x_continuous(
      labels = seq(from = -.2, to = .6, by = .2),
      breaks = seq(from = -.2, to = .6, by = .2)
    ) +
    #coord_cartesian(xlim = c(-0.15, 0.6)) +
    ggplot2::theme(
      plot.title = ggplot2::element_text(size = 13),
      axis.title.x = ggplot2::element_text(vjust = -1, size = 10),
      axis.title.y = ggplot2::element_text(vjust = +2, size = 10),
      axis.text.y = ggplot2::element_text(size = 9, face = "plain"),
      axis.text.x = ggplot2::element_text(size = 9, face = "plain"),
      panel.background = ggplot2::element_rect(
        fill = "white", color = "black", linetype = "solid"
      ),
      plot.background = ggplot2::element_rect(fill = "white"),
      panel.grid.major.y = ggplot2::element_blank(),
      panel.border = ggplot2::element_rect(
        color = "black", fill = NA, size = 5
      ),
      panel.spacing.x = unit(x = 3, units = "cm"),
      panel.spacing.y = unit(x = 3, units = "cm"),
      strip.background = ggplot2::element_rect(
        color = "black", fill = "gray"
      ),
      plot.margin = grid::unit(c(1, 1, 1, 1), "lines")
    )

  #### losers plot
  losers_plot <- ggplot2::ggplot(
    data = df_betas, mapping = ggplot2::aes(x = losers_beta)
  ) +
    ggplot2::geom_density(color = "black", fill = "gray") +
    ggplot2::geom_vline(
      xintercept = actual_est_losers, linetype = "dashed", size = 1
    ) +
    ggplot2::geom_segment(ggplot2::aes(
      x = actual_est_losers - 0.05,
      xend = actual_est_losers + 0,
      y = 15,
      yend = 15
    ),
    arrow = ggplot2::arrow(length = unit(2, "mm"))) +
    ggplot2::annotate(
      geom = "text", x = actual_est_losers - .055, y = 15,
      label = "Observed difference", hjust = "right"
    ) +
    ggplot2::annotate(
      geom = "text", x = actual_est_losers - .055, y = 14,
      label = paste0("(p-value=", round(pv_losers, 2), ")"),
      hjust = "right"
    ) +
    ggplot2::labs(
      title = "Electoral Losers",
      x = "Difference in Satisfaction with Democracy",
      y = "Density"
    ) +
    ggplot2::scale_x_continuous(
      labels = seq(from = -.2, to = .1, by = .1),
      breaks = seq(from = -.2, to = .1, by = .1)
    ) +
    #coord_cartesian(xlim = c(-0.2, 0.2)) +
    ggplot2::theme(
      plot.title = ggplot2::element_text(size = 13),
      axis.title.x = ggplot2::element_text(vjust = -1, size = 10),
      axis.title.y = ggplot2::element_text(vjust = +2, size = 10),
      axis.text.y = ggplot2::element_text(size = 9, face = "plain"),
      axis.text.x = ggplot2::element_text(size = 9, face = "plain"),
      panel.background = ggplot2::element_rect(
        fill = "white", color = "black", linetype = "solid"
      ),
      plot.background = element_rect(fill = "white"),
      panel.grid.major.y = ggplot2::element_blank(),
      panel.border = ggplot2::element_rect(
        color = "black", fill = NA, size = 5
      ),
      panel.spacing.x = unit(x = 3, units = "cm"),
      panel.spacing.y = unit(x = 3, units = "cm"),
      strip.background = ggplot2::element_rect(
        color = "black", fill = "gray"
      ),
      plot.margin = grid::unit(c(1, 1, 1, 1), "lines")
    )

  p <- ggpubr::ggarrange( # nolint
    widths = c(1, 1),
    winners_plot, losers_plot,
    ncol = 2, nrow = 1
  )

  ggplot2::ggsave(
    filename = "./figures/placebo_analysis.png",
    device = "png",
    width = 20,
    height = 8,
    units = "cm",
    dpi = 600
  )

}